﻿using System;
using System.Collections.Generic;
using System.Text;
using Bunian.Core;
using Bunian.Core.Repositories;
using NHibernate;
using WorkContext;

namespace Bunian.Data.NHibernate
{
    public class NhibernateRepository<T> : IRepository<T> //where T : BusinessObject<T>
    {   // copyrights (c) 2011-2015 Yazan Malakha
        // twitter: @ymj

        #region IRepository<T> Members

        public virtual void Save(T businessObj)
        {
            ISession session = WorkContext.NHibernateSessionManager.Instance.GetSession();
            
            //TODO-Tamim: Temporary, just to finish testing the Hierarchy mapping.
            //if (!businessObj.IsPersisted)
                session.Save(businessObj);
            //else
            //    session.SaveOrUpdateCopy(businessObj);

            session.Flush();
        }

        public virtual void Delete(T businessObj)
        {
            ISession session = WorkContext.NHibernateSessionManager.Instance.GetSession();
            
            session.Delete(businessObj);
            session.Flush();
        }

        /// <summary>
        /// Returns a valid populated object or a null reference        
        /// </summary>        
        public T Get(long id)
        {
            if (id <= 0)
                return default(T);
            else
            {
                ISession session = WorkContext.NHibernateSessionManager.Instance.GetSession();
                return session.Get<T>(id);
            }
        }
        public IList<T> ListAll(int pageSize)
        {
            ISession session = WorkContext.NHibernateSessionManager.Instance.GetSession();
            return session.CreateCriteria(typeof(T)).List<T>();
        }
        #endregion
    }
}
